package util;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

public class DEMO1 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection= DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8"
                            +"&allowPublicKeyRetrieval=true&useSSL=false",
                    "root",
                    "zyh22730267");
            statement=connection.createStatement();
            System.out.println("请输入你想要查询的学生姓名");
            String inName=scanner.nextLine();
            String sql="select id,name,sno,age,gender,enroll_date,class_id from student where name='"+inName+ "'";
            resultSet= statement.executeQuery(sql);
            while (resultSet.next()){
                //下标从1开始注意
                long id=resultSet.getLong("id");
                String name=resultSet.getString(2);
                String sno=resultSet.getString(3);
                int age=resultSet.getInt(4);
                byte gender=resultSet.getByte(5);
                Date enroll_date=resultSet.getDate(6);
                long class_id =resultSet.getLong(7);
                System.out.println(MessageFormat.format("学生编号{0} 学生姓名{1} 学号(2) 年龄{3} 性别{4} 入学时间{5} 班级编号{6} ",
                        id,name,sno,age,gender,enroll_date,class_id));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if (connection == null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (statement == null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (resultSet == null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            scanner.close();
        }
    }
}
